package com.tcoiss.webservice.utils;

import com.alibaba.fastjson.JSONObject;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.webservice.config.wx.config.AccessTokenConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class WeChatUtils {
    @Autowired
    private AccessTokenConfig accessTokenConfig;
    @Autowired
    private UrlConnectionUtils urlConnectionUtils;

    /**
    *以下是WeChatUtils类中的变量和方法
    * */

    //access_token为微信的接口调用授权码，此为企业号应用的access_token，本质上与企业access_token是一致的，只是获取方式不同
    public static String access_token;

    //jsapi_ticket为调用接口的临时票据，js调用接口时的权限验证,此为企业号应用的jsapi_ticket
    public static String jsapi_ticket;

    //获取access_token的方法，企业内部开发获取的方式
    public void getAccessToken() throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        //拼接参数，转义参数
//            String connUrl = "https://api.weixin.qq.com/cgi-bin/token" +
//                    "?grant_type=client_credential&appid=wx9feec909cc44cf13&secret="+ URLEncoder.encode("46845c894f6701b2718fcf73b2e840dc","UTF-8");
//                    +
//                    "?corpid=" + URLEncoder.encode(accessTokenConfig.getCorpid(),"UTF-8") +
//                    "&corpsecret=" + URLEncoder.encode(accessTokenConfig.getCorpsecret(),"UTF-8");
        String conUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("corpid",accessTokenConfig.getCorpid());
        map.put("corpsecret",accessTokenConfig.getCorpsecret());
        //获取并解析数据
        rs = urlConnectionUtils.requestGetData(conUrl,map);
        JSONObject jo = JSONObject.parseObject(rs);
        String access_token = jo.getString("access_token");
        //accessTokenConfig.access_token = jo.getString("access_token");
        //System.out.println("accessTokenConfig.access_token:"+accessTokenConfig.access_token);
        //System.out.println("access_token:" + access_token);
        //System.out.println("rs:" + rs);
        if(StringUtils.isBlank(access_token)){
            System.out.println("获取access_token失败！");
        }else{
            this.access_token =  access_token;
            System.out.println("获取access_token成功！");
            System.out.println("access_token："+access_token);
        }
    }

    //获取jsapi_ticket的方法
    public void getJsapiTicket() throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        //拼接参数，转义参数
        String conUrl = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("access_token",this.access_token);
        /*该url返回的result
        {
            "errcode":0,
                "errmsg":"ok",
                "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
                "expires_in":7200
        }*/
        //获取并解析数据
        rs = urlConnectionUtils.requestGetData(conUrl,map);
        JSONObject jo = JSONObject.parseObject(rs);
        String jsapi_ticket = jo.getString("ticket");
        //accessTokenConfig.access_token = jo.getString("access_token");
        //System.out.println("accessTokenConfig.access_token:"+accessTokenConfig.access_token);
        //System.out.println("access_token:" + access_token);
        //System.out.println("rs:" + rs);
        if(StringUtils.isBlank(jsapi_ticket)){
            System.out.println("获取jsapi_ticket失败！");
        }else{
            this.jsapi_ticket =  jsapi_ticket;
            System.out.println("获取jsapi_ticket成功！");
            System.out.println("jsapi_ticket："+jsapi_ticket);
        }
    }

    public String sendMessage(Object objMessage){
        String url = accessTokenConfig.getWechat_send_url() + this.access_token;
        try {
            String s = urlConnectionUtils.httpClientPost(url,objMessage);
            System.out.println("s:"+s);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @Title: getNonceStr
     * @Description: 生成随机字符串
     * @param @return
     * @return String    返回类型
     * @throws
     */
    public static String getNonceStr() {
        String currT = getCurrTime();
        String strT = currT.substring(8, currT.length());
        String strRandom = buildRandom(4) + "";
        return strT + strRandom;
    }


    /**
     *
     * @Title: buildRandom
     * @Description: 生成随机数
     * @param @param length
     * @param @return
     * @return int    返回类型
     * @throws
     */
    public static int buildRandom(int length) {
        int mm= 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            mm= mm* 10;
        }
        return (int) ((random * mm));
    }


    /**
     *
     * @Title: getCurrTime
     * @Description: 获取当前时间
     * @param @return
     * @return String    返回类型
     * @throws
     */
    public static String getCurrTime() {
        Date date = new Date();
        SimpleDateFormat of= new SimpleDateFormat("yyyyMMddHHmmss");
        String s = of.format(date);
        return s;
    }

    /**
     *
     * @Title: createSignBySha1
     * @Description: 生成签名
     * @param @param params
     * @param @return
     * @return String    返回类型
     * @throws
     */
    @SuppressWarnings("rawtypes")
    public static String createSignBySha1(SortedMap<Object, Object> params) {
        StringBuffer sb = new StringBuffer();
        Set es = params.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (v != null && !v.equals("")) {
                sb.append(k + "=" + v + "&");
            }
        }
        String result = sb.toString().substring(0, sb.toString().length()-1);
        return getSHA1(result);
    }
    /**
     *
     * @Title: getTimestamp
     * @Description: 获取时间戳(秒)
     * @param @return    参数
     * @return String    返回类型
     * @throws
     */
    public static String getTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     *
     * @Title: getSHA1
     * @Description: SHA1签名生成
     * @param @param str
     * @param @return    参数
     * @return String    返回类型
     * @throws
     */
    public static String getSHA1(String str){
        StringBuffer hexstr = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hexstr.toString();
    }

}
